package yancy.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import yancy.common.utils.Constant;
import yancy.common.utils.PageUtils;
import yancy.common.utils.Query;
import yancy.modules.sys.dao.SysBookDao;
import yancy.modules.sys.entity.SysBook;
import yancy.modules.sys.entity.SysFile;
import yancy.modules.sys.service.SysBookAuthorService;
import yancy.modules.sys.service.SysBookFileService;
import yancy.modules.sys.service.SysBookService;
import yancy.modules.sys.service.SysFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysBookServiceImpl extends ServiceImpl<SysBookDao, SysBook>
        implements SysBookService {

    @Autowired
    private SysBookAuthorService bookAuthorService;
    @Autowired
    private SysBookFileService bookFileService;
    @Autowired
    private SysFileService fileService;

    @Override
    public Page query(Page p, Map<String, Object> params) {
        List<SysBook> books = this.baseMapper.query(p, params);
        List<Integer> fileIds = books.stream()
            .map(SysBook::getFileIds)
            .filter(StringUtils::isNumeric)
            .map(Integer::valueOf)
            .collect(Collectors.toList());

        List<SysFile> files = fileService.list(new QueryWrapper<SysFile>().in(CollectionUtils.isNotEmpty(fileIds), "file_id", fileIds));
        if(CollectionUtils.isNotEmpty(files)){
            for (SysBook book : books) {
                if(!StringUtils.isNumeric(book.getFileIds()))
                    continue;
                for (SysFile file : files) {
                    if (Integer.parseInt(book.getFileIds()) == file.getFileId()) {
                        book.setFileList(Collections.singletonList(file));
                        break;
                    }
                }
            }
        }

        return p.setRecords(books);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String) params.get("name");
        Long createUserId = (Long) params.get("createUserId");

        IPage<SysBook> page = this.page(
                new Query<SysBook>().getPage(params),
                new QueryWrapper<SysBook>()
                        .like(StringUtils.isNotBlank(username), "name", username)
                        .eq(createUserId != null, "create_user_id", createUserId)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveBook(SysBook book) {
        book.setCreateTime(new Date());
        book.setAvailable(book.getTotal());
        this.save(book);

        //检查角色是否越权
        checkAuthor(book);

        //保存用户与角色关系sysUserRoleService
        bookAuthorService.saveOrUpdate(book.getBookId(), book.getAuthorIdList());
        bookFileService.saveOrUpdate(book.getBookId(), book.getFileIdList());
    }


    @Override
    @Transactional
    public void update(SysBook book) {
        SysBook oldBook = this.getById(book.getBookId());
        Integer pad = book.getTotal() - oldBook.getTotal();
        Integer curAvailable = oldBook.getAvailable() + pad;

        if (curAvailable < 0)
            curAvailable = 0;
        else if (curAvailable > book.getTotal())
            curAvailable = book.getTotal();

        book.setAvailable(curAvailable);
        this.updateById(book);


//        updateAvailable(b);

        //检查角色是否越权
        checkAuthor(book);

        //保存用户与角色关系
        bookAuthorService.saveOrUpdate(book.getBookId(), book.getAuthorIdList());
        bookFileService.saveOrUpdate(book.getBookId(), book.getFileIdList());

    }

    private void updateAvailable(SysBook b) {
        if (b.getTotal() < b.getAvailable()) {
            b.setAvailable(b.getTotal());
        }
        this.save(b);
    }


    private void checkAuthor(SysBook book) {
        if (book.getAuthorIdList() == null || book.getAuthorIdList().size() == 0) {
            return;
        }
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if (book.getCreateUserId() == Constant.SUPER_ADMIN) {
            log.error("cannot create author and book relationship");
            return;
        }

    }
    private boolean canDeleted(Long authorId) {
        Integer ref = baseMapper.hasReference(authorId);
        return ref == null || ref == 0;
    }


    @Override
    public boolean deleteById(Long bookId) {
        if (!canDeleted(bookId)) {
            return false;
        }
        log.info("authorId {} was deleted", bookId);
        baseMapper.deleteById(bookId);
        return true;
    }
}




